前端analysis | What,Why,Who,When,Where,How

《angular8》- angular8 ui-grid升级方案

2020-04-24

方案一

方案二

使用背景

  • 技术需要升级angularjs → angular8
  • 没有可用的Ui组件
  • 或者有可用的Ui组件,但是由于某些限制,譬如公司级别技术要求,不给使用

只能使用angular directive

  • 定义ui-grid所在angularjs组件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    export const heroDetail = {
    bindings: {
    hero: '<',
    deleted: '&'
    },
    template: `
    <h2>{{$ctrl.hero.name}} details!</h2>
    <div><label>id: </label>{{$ctrl.hero.id}}</div>
    <button ng-click="$ctrl.onDelete()">Delete</button>
    `,
    controller: function() {
    this.onDelete = () => {
    this.deleted(this.hero);
    };
    }
    };
  • 定义angular8 directive

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    import { Directive, ElementRef, Injector, Input, Output, EventEmitter } from '@angular/core';
    import { UpgradeComponent } from '@angular/upgrade/static';
    import { Hero } from '../hero';

    @Directive({
    selector: 'hero-detail'
    })
    export class HeroDetailDirective extends UpgradeComponent {
    @Input() hero: Hero;
    @Output() deleted: EventEmitter<Hero>;

    constructor(elementRef: ElementRef, injector: Injector) {
    super('heroDetail', elementRef, injector);
    }
    }
    • 需要扩展UpgradeComponent组件
    • 需要调用super方法,传递参数给angularjs组件
    • 上面例子,heroDetail,是angularjs中注册的组件的名称。
  • ngModule中声明

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    @NgModule({
    imports: [
    BrowserModule,
    UpgradeModule
    ],
    declarations: [
    HeroDetailDirective,
    /* . . . */
    ]
    })
    export class AppModule {
    constructor(private upgrade: UpgradeModule) { }
    ngDoBootstrap() {
    this.upgrade.bootstrap(document.body, ['heroApp'], { strictDi: true });
    }
    }
  • 定义外层容器,使用directive

  • ContainerComponent 需要在appModule declaration中定义

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    import { Component } from '@angular/core';
    import { Hero } from '../hero';

    @Component({
    selector: 'my-container',
    template: `
    <h1>Tour of Heroes</h1>
    <hero-detail [hero]="hero"
    (deleted)="heroDeleted($event)">
    </hero-detail>
    `
    })
    export class ContainerComponent {
    hero = new Hero(1, 'Windstorm');
    heroDeleted(hero: Hero) {
    hero.name = 'Ex-' + hero.name;
    }
    }

更多推荐

参考

使用支付宝打赏
使用微信打赏

若你觉得我的文章对你有帮助,欢迎点击上方按钮对我打赏